<?php
namespace app\Logic;


class OpensslLogic extends Logic
{
    private $privateKeyFilePath;

    private $publicKeyFilePath;

    public function __construct()
    {
        //$this->privateKeyFilePath = ROOT_PATH . 'rsa_public_key.pem';
        $this->publicKeyFilePath = ROOT_PATH . 'rsa_public_key.pem';
        var_dump($this->publicKeyFilePath);die;
    }

    public static function encrypt($originalData)
    {
        $self = new static();
        $privateKeyFilePath = $self->privateKeyFilePath;
        if(!extension_loaded('openssl')){
            self::$error = 'php需要openssl扩展支持';
            return false;
        }
        if(!file_exists($privateKeyFilePath)){
            self::$error = '密钥的文件路径不正确';
            return false;
        }
        $privateKey = openssl_pkey_get_private(file_get_contents($privateKeyFilePath));
        if(!$privateKey){
            self::$error = '密钥不可用';
            return false;
        }
        $encryptData = '';
        if (openssl_private_encrypt($originalData, $encryptData, $privateKey)) {
            return base64_encode($encryptData);
        } else {
            return false;
        }
    }


    public static function decode($encryptData)
    {
        $self = new static();
        $publicKeyFilePath = $self->publicKeyFilePath;
        if(!extension_loaded('openssl')){
            self::$error = 'php需要openssl扩展支持';
            return false;
        }
        if(!file_exists($publicKeyFilePath)){
            self::$error = '公钥的文件路径不正确';
            return false;
        }
        $publicKey = openssl_pkey_get_private(file_get_contents($publicKeyFilePath));
        if(!$publicKey){
            self::$error = '公钥不可用';
            return false;
        }

        if (openssl_public_decrypt($encryptData, $decryptData, $publicKey)) {
            return $decryptData;
        } else {
            return false;
        }
    }
}